package com.springboot.service;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

import java.util.Calendar;

import java.util.Collections;

import java.util.Date;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import com.springboot.dao.AnnounceMapper;

import com.springboot.entity.Announce;

import com.springboot.entity.AnnounceExample;

import com.springboot.entity.*;
import com.springboot.dao.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;

@Service

public class AnnounceService implements AnnounceServiceImp {


    private static final Log logger = LogFactory.getLog(AnnounceService.class);

    @Autowired
    private AnnounceMapper announcedao;


    //定义方法addannounce,响应控制层addannounce请求

    public void addannounce(HttpServletRequest request, HttpSession session) {

        //输出日志，当前执行方法为addannounce

        logger.debug("AnnounceService.addannounce ......");


    }


    //定义addannounceact方法

    public void addannounceact(HttpServletRequest request, HttpSession session, Announce announce, MultipartFile picfile) throws IOException {

        //输出当前方法日志，表示正在执行AnnounceService.addannounceact方法

        logger.debug("AnnounceService.addannounceact ......");

// 判断图片文件是否为空  

        if (!picfile.isEmpty()) {

// 调用uploadUtile方法将页面传入的图片文件上传到服务器，将返回的文件名保存到pic参数中  

            String pic = uploadUtile(picfile, request);

// 将announce的图片设置为pic的值  

            announce.setPic(pic);

        }


        //使用announcedao的insert方法将公告添加到数据库中

        announcedao.insert(announce);


        //将添加公告信息添加到request中用message参数进行保存

        request.setAttribute("message", "添加公告成功");

    } //定义addannounceactjson方法

    public void addannounceactjson(Announce announce) throws IOException {

        //输出当前方法日志，表示正在执行AnnounceService.addannounceactjson方法

        logger.debug("AnnounceService.addannounceactjson ......");

        //使用announcedao的insert方法将公告添加到数据库中

        announcedao.insert(announce);

    }


    //定义announcemanage方法响应页面请求

    public void announcemanage(HttpServletRequest request, HttpSession session) {

        //输出日志，表示当前正在执行AnnounceService.announcemanage

        logger.debug("AnnounceService.announcemanage ......");


        //实例化AnnounceExample类为example

        AnnounceExample example = new AnnounceExample();


        //使用  announcedao.selectByExample(example)方法获取所有的公告数据

        List announceall = announcedao.selectByExample(example);


        //将所有的公告数据保存到request中的announceall参数里

        request.setAttribute("announceall", announceall);


    }


    // 定义 announceview方法

    public void announceview(HttpServletRequest request, HttpSession session) {

        // 输出日志，表示当前正在执行AnnounceService.announceview方法

        logger.debug("AnnounceService.announceview ......");


        // 实例化AnnounceExample类

        AnnounceExample example = new AnnounceExample();


        // 使用announcedao的selectByExample方法查询公告信息

        List announceall = announcedao.selectByExample(example);


        // 将查询的announceall保存到request中，记录为参数announceall

        request.setAttribute("announceall", announceall);


    }


    // 定义 updateannounce方法

    public void updateannounce(HttpServletRequest request, HttpSession session, int id) {

        // 输出日志AnnounceController.updateannounce，表示正在执行该方法

        logger.debug("AnnounceController.updateannounce ......");


        // 定义公告为biaoming，使用 announcedao的selectByPrimaryKey方法通过id查询数据

        Announce announce = announcedao.selectByPrimaryKey(id);


        // 将查询的公告保存到request中

        request.setAttribute("announce", announce);


    }


    // 定义updateannounceact处理公告修改

    public void updateannounceact(HttpServletRequest request, Announce announce, HttpSession session, MultipartFile picfile) throws IOException {

        // 输出日志，表示正在执行当前方法AnnounceController.updateannounceact

        logger.debug("AnnounceController.updateannounceact ......");

// 判断图片文件是否为空  

        if (!picfile.isEmpty()) {

// 调用uploadUtile方法将页面传入的图片文件上传到服务器，将返回的文件名保存到pic参数中  

            String pic = uploadUtile(picfile, request);

// 将announce的图片设置为pic的值  

            announce.setPic(pic);

        }


        // 执行announcedao的updateByPrimaryKeySelective方法，将传入的公告数据同步到数据库中

        announcedao.updateByPrimaryKeySelective(announce);


        // 将修改成功信息保存到request中

        request.setAttribute("message", "修改公告信息成功");


    } // 定义updateannounceactjson处理公告修改

    public void updateannounceactjson(Announce announce) throws IOException {

        // 输出日志，表示正在执行当前方法AnnounceController.updateannounceactjson

        logger.debug("AnnounceController.updateannounceactjson ......");

        // 执行announcedao的updateByPrimaryKeySelective方法，将传入的公告数据同步到数据库中

        announcedao.updateByPrimaryKeySelective(announce);

    }


    // 定义deleteannounce,处理删除公告

    public void deleteannounce(HttpServletRequest request, HttpSession session, int id) {

        // 输出日志，表示当前正在执行AnnounceService.deleteannounce方法

        logger.debug("AnnounceService.deleteannounce ......");

        //如果传入的id为-1，表示进行批量删除
        if (id == -1) {
            //实例化公告example
            AnnounceExample example = new AnnounceExample();
            //获取到传递过来的ids数据信息
            String ids = request.getParameter("ids");
            //为id信息添加-1数据，添加此数据可以防止数据为空时的报错
            ids += "-1,";
            //截取掉多余的逗号
            ids.substring(0, ids.length() - 1);
            //设置where语句进行删除id数据的传入
            //example.setWhere("id in ("+ ids +")");
            //实例化公告criteria
            AnnounceExample.Criteria criteria = example.createCriteria();
            //设置integer类型的数组，保存需要删除的公告id信息
            List<Integer> idlist = new ArrayList();
            //根据id分离出需要删除的数据id信息
            String[] idarr = ids.split(",");
            //将对应的id数据信息保存到数组中
            for (int i = 0; i < idarr.length; i++) {
                //取出对应的id信息，并转换成int类型
                idlist.add(Integer.parseInt(idarr[i]));
            }
            //传入需要删除的id数组信息
            criteria.andIdIn(idlist);
            //调用公告的dao类，执行批量删除操作
            announcedao.deleteByExample(example);
        } else {
            // 根据id调用announcedao的deleteByPrimaryKey方法，删除公告


            announcedao.deleteByPrimaryKey(id);

        }


        request.setAttribute("message", "删除公告成功");


    }


    // 定义searchannounce方法，处理搜索操作

    public void searchannounce(HttpServletRequest request, HttpSession session, String search) {

        // 输出日志，表示当前正在执行AnnounceService.searchannounce

        logger.debug("AnnounceService.searchannounce ......");


        // 实例化 AnnounceExample

        AnnounceExample example = new AnnounceExample();

        // 实例化 AnnounceExample的Criteria内部类

        AnnounceExample.Criteria criteria = example.createCriteria();

        // 如果搜索内容不等于空

        if (search != null) {

            // 将搜索内容通过like关键字传到数据库中进行搜索

            criteria.andTitleLike("%" + search + "%");

        }

        // 查询公告结果

        List announceall = announcedao.selectByExample(example);

        // 将查询到的公告 保存到request中进行保存

        request.setAttribute("announceall", announceall);

    }


    // 定义searchannouncejson方法，处理搜索操作

    public Map searchannouncejson(String search) {

        // 输出日志，表示当前正在执行AnnounceService.searchannouncejson

        logger.debug("AnnounceService.searchannouncejson ......");

        // 定义返回结果

        Map result = new HashMap();

        // 实例化 AnnounceExample

        AnnounceExample example = new AnnounceExample();

        // 实例化 AnnounceExample的Criteria内部类

        AnnounceExample.Criteria criteria = example.createCriteria();

        // 如果搜索内容不等于空

        if (search != null) {

            // 将搜索内容通过like关键字传到数据库中进行搜索

            criteria.andTitleLike("%" + search + "%");

        }

        // 查询公告结果

        List announceall = announcedao.selectByExample(example);

        // 将查询到的公告 保存到request中进行保存

        result.put("announceall", announceall);

        // 返回查询结果resultmap

        return result;

    }


    // 定义AnnouncepinglunMapper

    public void announcedetails(HttpServletRequest request, HttpSession session, int id) {

        // 输入日志信息，表名当前执行方法为AnnounceController.announcedetails

        logger.debug("AnnounceController.announcedetails ......");


        // 传入页面所传入的公告id使用announcedao的selectByPrimaryKey方法进行查询

        Announce announce = announcedao.selectByPrimaryKey(id);

        // 将查询到的公告保存到request中

        request.setAttribute("announce", announce);


    }


    // 定义Announce详情方法

    public Map announcedetailsjson(int id) {

        // 输入日志信息，表名当前执行方法为AnnounceController.announcedetailsjson

        logger.debug("AnnounceController.announcedetailsjson ......");


        // 定义返回结果

        Map result = new HashMap();

        // 传入页面所传入的公告id使用announcedao的selectByPrimaryKey方法进行查询

        Announce announce = announcedao.selectByPrimaryKey(id);

        // 将查询到的公告保存到result中

        result.put("announce", announce);


        // 返回查询结果resultmap

        return result;

    }


//	上传文件图片等

    public String uploadUtile(MultipartFile file, HttpServletRequest request) throws IOException {

        // 根据当前时间生成时间字符串

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");

        String res = sdf.format(new Date());

        // uploads文件夹位置

        String tomcatroot = request.getSession().getServletContext().getRealPath("resource/uploads/");
        String localroot = request.getServletContext().getRealPath("").split("out")[0] + "WebRoot/resource/uploads";
        System.out.println(tomcatroot);
        System.out.println(localroot);

        // 原始名称

        String originalFileName = file.getOriginalFilename();

        // 新文件名

        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));

        // 创建年月文件夹

        Calendar date = Calendar.getInstance();

        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

        // 新文件

        File tomcatFile = new File(tomcatroot + File.separator + dateDirs + File.separator + newFileName);
        File localFile = new File(localroot + File.separator + dateDirs + File.separator + newFileName);

        // 判断目标文件所在目录是否存在

        if (!tomcatFile.getParentFile().exists()) {

            // 如果目标文件所在的目录不存在，则创建父目录

            tomcatFile.getParentFile().mkdirs();

        }
        // 判断目标文件所在目录是否存在

        if (!localFile.getParentFile().exists()) {

            // 如果目标文件所在的目录不存在，则创建父目录

            localFile.getParentFile().mkdirs();

        }

        file.transferTo(tomcatFile);

        String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + newFileName;

        return fileUrl;

    }
}

